<?php

namespace app\ask\controller;

use think\Controller;

class Post extends Controller
{
  public function __construct()
  {
    parent::__construct();

    $this->BusinessModel = model('Business.Business');
    $this->PostModel = model('Post.Post');
    $this->CollectModel = model('Post.Collect');
    $this->CommentModel = model('Post.Comment');
    $this->AttentionModel = model('Post.Attention');
    $this->FansModel = model('Post.Fans');
  }

  // 查询帖子表数据(首页)
  /**
   * 思路
   * 1.判断请求，接收数据
   * 2.设置限制行数，设置偏移量，设置判断的条件
   * 3.模糊搜索，关键字搜索
   * 3.查询出所有的帖子数量
   */
  public function index()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数
      $page = $this->request->param('page', 1, 'trim');
      $cateid = $this->request->param('cateid', 0, 'trim');
      $keywords = $this->request->param('keywords', '', 'trim');
      $limit = 7;

      // 设置偏移量
      $offset = ($page - 1) * $limit;

      $where = [];

      // 判断是否有id，且如果有当选项卡的id发送变化的时候，则查询的数据就不同
      if ($cateid) {
        $where['cateid'] = $cateid;
      }

      if (!empty($keywords)) {
        $where['title'] = ['like', "%$keywords%"];
      }

      // 查询帖子表中的数据
      $list = $this->PostModel
        ->with(['cate', 'business'])
        ->where($where)
        ->order('id', 'desc')
        ->limit($offset, $limit)
        ->select();

      if ($list) {
        $this->success('返回帖子数据', null, $list);
        exit;
      } else {
        $this->error('暂无更多数据');
        exit;
      }
    }
  }

  // 发帖子
  /**
   * 思路： 
   * 1.先拿到发帖子的数据，去进行判断
   * 2.悬赏需要去判断积分是否足够（进行相减）
   * 3.然后就是插入帖子表和更新用户表了
   * 帖子表
   * 用户表
   */
  public function add()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数
      $title = $this->request->param('title', '', 'trim');
      $content = $this->request->param('content', '', 'trim');
      $point = $this->request->param('point', 0, 'trim');
      $cateid = $this->request->param('cateid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');

      // 判断用户是否存在
      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      // 悬赏需要扣除积分，进行积分的删减
      $UpdatePoint = bcsub($business['point'], $point);

      // 积分不足
      if ($UpdatePoint < 0) {
        $this->error('积分不足，请先充值');
        exit;
      }

      // 帖子表、用户表
      $this->PostModel->startTrans();
      $this->BusinessModel->startTrans();

      // 组装帖子表数据
      $PostData = [
        'title' => $title,
        'content' => $content,
        'point' => $point,
        'busid' => $busid,
        'cateid' => $cateid,
        'status' => '0',
      ];

      // 插入帖子表
      $PostStatus = $this->PostModel->save($PostData);

      if ($PostStatus === FALSE) {
        $this->error($this->PostModel->getError());
        exit;
      }

      // 组装用户数据
      $BusinessData = [
        'id' => $busid,
        'point' => $UpdatePoint
      ];

      // 更新用户表
      $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

      if ($BusinessStatus === FALSE) {
        $this->PostModel->rollback();
        $this->error($this->BusinessModel->getError());
        exit;
      }

      if ($PostStatus === FALSE || $BusinessStatus === FALSE) {
        $this->BusinessModel->rollback();
        $this->PostModel->rollback();
        $this->error('发帖失败');
        exit;
      } else {
        $this->PostModel->commit();
        $this->BusinessModel->commit();
        $this->success('发帖成功', '/pages/post/info', ['postid' => $this->PostModel->id]);
        exit;
      }
    }
  }

  // 编辑帖子
  public function edit()
  {
    if ($this->request->isPost()) {
      $title = $this->request->param('title', '', 'trim');
      $content = $this->request->param('content', '', 'trim');
      $point = $this->request->param('point', 0, 'trim');
      $cateid = $this->request->param('cateid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');
      $postid = $this->request->param('postid', 0, 'trim');


      //确保用户是否存在
      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      //确保帖子是存在
      $post = $this->PostModel->where(['id' => $postid, 'busid' => $busid])->find();

      if (!$post) {
        $this->error('帖子不存在');
        exit;
      }


      //查看用户积分是否充足
      $UpdatePoint = bcsub($business['point'], $point);

      if ($UpdatePoint < 0) {
        $this->error('积分不足，请先充值');
        exit;
      }

      //帖子表、用户表、消费记录表
      $this->PostModel->startTrans();
      $this->BusinessModel->startTrans();

      //编辑帖子
      $PostData = [
        'id' => $postid,
        'title' => $title,
        'content' => $content,
        'busid' => $busid,
        'cateid' => $cateid,
        'status' => '0',
      ];

      //积分
      if ($point > 0) {
        // 这里相当于，在原始的基础上进行加
        $PostData['point'] = bcadd($post['point'], $point);
      }

      $PostStatus = $this->PostModel->isUpdate(true)->save($PostData);

      if ($PostStatus === FALSE) {
        $this->error($this->PostModel->getError());
        exit;
      }

      //更新用户积分
      $BusinessData = [
        'id' => $busid,
        'point' => $UpdatePoint
      ];

      $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($BusinessData);

      if ($BusinessStatus === FALSE) {
        $this->PostModel->rollback();
        $this->error($this->BusinessModel->getError());
        exit;
      }

      if ($PostStatus === FALSE || $BusinessStatus === FALSE) {
        $this->BusinessModel->rollback();
        $this->PostModel->rollback();
        $this->error('编辑帖子失败');
        exit;
      } else {
        $this->PostModel->commit();
        $this->BusinessModel->commit();
        $this->success('编辑帖子成功');
        exit;
      }
    }
  }

  //查询帖子分类
  public function cate()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      $list = model('Post.Cate')->order('weigh', 'asc')->select();

      if ($list) {
        $this->success('帖子分类', null, $list);
        exit;
      } else {
        $this->error('无帖子分类');
        exit;
      }
    }
  }

  // 帖子详情
  public function info()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数
      $postid = $this->request->param('postid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');

      // 查询当前帖子表的数据
      $post = $this->PostModel->with(['business', 'cate'])->find($postid);

      if (!$post) {
        $this->error('暂无帖子信息');
        exit;
      }

      // 查询用户信息
      $business = $this->BusinessModel->find($busid);

      //如果有找到用户信息
      if ($business) {
        //查询收藏的状态（根据帖子的id和用户的id，查找出当前用户是否有收藏过）
        $collect = model('Post.Collect')->where(['postid' => $postid, 'busid' => $busid])->find();

        // 组装条件
        $where = [];
        $where = [
          'attentionid' => $busid,
          'busid' => $post['busid']
        ];

        // 查询关注表状态
        $attention = model('Post.Attention')->where($where)->find();

        if ($collect) {
          //追加自定义数组元素
          $post['collect'] = true;
        }

        if ($attention) {
          //追加自定义数组元素
          $post['attention'] = true;
        }
      }

      $this->success('返回帖子信息', null, $post);
      exit;
    }
  }

  // 帖子收藏
  public function collect()
  {
    // 判断是否有post请
    if ($this->request->isPost()) {
      // 接收参数
      $postid = $this->request->param('postid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');

      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      // 判断条件
      $where = ['postid' => $postid, 'busid' => $busid];
      // 查询收集收藏表
      $collect = $this->CollectModel->where($where)->find();

      // 判断是否被收藏过
      if ($collect) {
        // 有收藏过，要取消收藏，将收藏表数据删除
        $result = $this->CollectModel->where(['id' => $collect['id']])->delete();

        // 
        if ($result === FALSE) {
          $this->error('取消收藏失败');
          exit;
        } else {
          $this->success('取消收藏成功');
          exit;
        }
      } else {
        // 没有收藏过，需要新增插入
        //没收藏过  要新增插入
        $result = $this->CollectModel->save(['busid' => $busid, 'postid' => $postid]);

        if ($result === FALSE) {
          $this->error('收藏失败');
          exit;
        } else {
          $this->success('收藏成功');
          exit;
        }
      }
    }
  }

  // 点赞评论
  public function like()
  {
    if ($this->request->isPost()) {
      $postid = $this->request->param('postid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');
      $comid = $this->request->param('comid', 0, 'trim');

      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      $comment = $this->CommentModel->find($comid);

      if (!$comment) {
        $this->error('评论不存在');
        exit;
      }

      $data = [
        'id' => $comid,
      ];

      //将评论表中的字符串赋值给这个变量(9,10,11)
      $like_list = $comment['like_list'];

      //判断元素是否在数组内
      if (in_array($busid, $like_list)) {
        //如果有找到就说明点个赞，就是要取消点赞
        $index = array_search($busid, $like_list);
        unset($like_list[$index]);
      } else {
        // 将点赞的这个用户id，存入这个数组中
        $like_list[] = $busid;
      }

      // 判断点赞是否为空
      if (empty($like_list)) {
        $data['like'] = NULL;
      } else {
        // 去掉逗号，插入到like这个字段里面
        $data['like'] = implode(',', $like_list);
      }

      //更新
      $result = $this->CommentModel->isUpdate(true)->save($data);

      if ($result === FALSE) {
        $this->error('点赞失败');
        exit;
      } else {
        $this->success('点赞成功');
        exit;
      }
    }
  }

  // 采纳
  public function accept()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数
      $comid = $this->request->param('comid', 0, 'trim');
      $postid = $this->request->param('postid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');

      // 判断
      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      $comment = $this->CommentModel->find($comid);

      if (!$comment) {
        $this->error('评论不存在');
        exit;
      }

      //采纳人的信息
      $acceptid = isset($comment['busid']) ? $comment['busid'] : 0;
      $accept = $this->BusinessModel->find($acceptid);

      if (!$accept) {
        $this->error('采纳人信息未知');
        exit;
      }

      $where = ['id' => $postid, 'busid' => $busid];
      $post = $this->PostModel->where($where)->find();

      if (!$post) {
        $this->error('帖子不存在');
        exit;
      }

      // 自己不能采纳自己的评论
      if ($acceptid == $busid) {
        $this->error('不能采纳自己的评论');
        exit;
      }

      /**
       * 帖子表（更新采纳人和状态）
       * 评论表（更新状态）
       * 用户表（更新积分）
       */

      // 开启事务
      $this->PostModel->startTrans();
      $this->CommentModel->startTrans();
      $this->BusinessModel->startTrans();

      //更新帖子表
      $PostData = [
        'id' => $post['id'],
        'status' => '1',
        'accept' => $acceptid,
      ];

      $PostStatus = $this->PostModel->isUpdate(true)->save($PostData);

      if ($PostStatus === FALSE) {
        $this->error($this->PostModel->getError());
        exit;
      }

      //评论表
      $CommentData = [
        'id' => $comid,
        'status' => '1',
      ];

      $CommentStatus = $this->CommentModel->isUpdate(true)->save($CommentData);

      if ($CommentStatus === FALSE) {
        $this->PostModel->rollback();
        $this->error($this->CommentModel->getError());
        exit;
      }

      //更新用户表
      $PostPoint = $post['point'];
      $BusPoint = $accept['point'];

      $UpdatePoint = bcadd($PostPoint, $BusPoint);

      $BusData = [
        'id' => $accept['id'],
        'point' => $UpdatePoint
      ];

      //更新用户积分
      $BusStatus = $this->BusinessModel->isUpdate(true)->save($BusData);

      if ($BusStatus === FALSE) {
        $this->CommentModel->rollback();
        $this->PostModel->rollback();
        $this->error($this->BusinessModel->getError());
        exit;
      }

      if ($PostStatus === FALSE || $CommentStatus === FALSE || $BusStatus === FALSE) {
        $this->BusinessModel->rollback();
        $this->CommentModel->rollback();
        $this->PostModel->rollback();
        $this->error('采纳失败');
        exit;
      } else {
        $this->PostModel->commit();
        $this->CommentModel->commit();
        $this->BusinessModel->commit();
        $this->success('采纳成功');
        exit;
      }
    }
  }

  // 关注用户
  public function attention()
  {
    // 判断是否有post请
    if ($this->request->isPost()) {
      // 接收参数
      $attentionid = $this->request->param('attentionid', 0, 'trim');
      $busid = $this->request->param('busid', 0, 'trim');
      $fansid = $this->request->param('fansid', 0, 'trim');

      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      // 查询粉丝表
      $attention = $this->AttentionModel->where(['attentionid' => $busid, 'busid' => $attentionid])->find();
      $fans = $this->FansModel->where(['fansid' => $attentionid, 'busid' => $fansid])->find();
      // var_dump($fans->toArray());
      // exit;

      // 判断是否被关注过
      if ($attention && $fans) {

        // 开启事务
        $this->AttentionModel->startTrans();
        $this->FansModel->startTrans();

        // 有关注过，要取消关注，将关注表中数据删除
        $AttentionStatus = $this->AttentionModel->where(['id' => $attention['id']])->delete();

        if ($AttentionStatus === FALSE) {
          $this->error($this->AttentionModel->getError());
          exit;
        }

        $FansStatus = $this->FansModel->where(['id' => $fans['id']])->delete();

        if ($FansStatus === FALSE) {
          $this->AttentionModel->rollback();
          $this->error($this->FansModel->getError());
          exit;
        }

        if ($FansStatus === FALSE || $AttentionStatus === FALSE) {
          $this->FansModel->rollback();
          $this->AttentionModel->rollback();
          $this->error('取消关注失败');
          exit;
        } else {
          $this->AttentionModel->commit();
          $this->FansModel->commit();
          $this->success('取消关注成功');
        }
      } else {
        if ($busid == $attentionid) {
          $this->error('不可以关注自己');
          exit;
        }

        // 开启事务
        $this->AttentionModel->startTrans();
        $this->FansModel->startTrans();

        // 组装数据
        $AttentionData = [
          'busid' => $attentionid,
          'attentionid' => $busid,
        ];

        $AttentionStatus = $this->AttentionModel->save($AttentionData);

        if ($AttentionStatus === FALSE) {
          $this->error($this->AttentionModel->getError());
          exit;
        }

        $FansData = [
          'busid' => $busid,
          'fansid' => $attentionid
        ];

        $FansStatus = $this->FansModel->save($FansData);

        if ($FansStatus === FALSE) {
          $this->AttentionModel->rollback();
          $this->error($this->FansModel->getError());
          exit;
        }

        if ($FansStatus === FALSE || $AttentionStatus === FALSE) {
          $this->FansModel->rollback();
          $this->AttentionModel->rollback();
          $this->error('关注失败');
          exit;
        } else {
          $this->AttentionModel->commit();
          $this->FansModel->commit();
          $this->success('关注成功');
        }
      }
    }
  }
}
